<template>
  <div class="new-order">
    <a-form :form="newOrderForm">
      <a-row>
        <a-col :span="24" class="pad_bot10 pad_top10 weight7">门店名称</a-col>
      </a-row>
      <a-row>
        <a-col :span="16" >
          <a-form-item>
            <a-input
              placeholder="请输入门店名称"
              v-decorator="['mdmc', {
                rules: [{ required: true, message: '必填',whitespace: true}],
                initialValue: order&&order.mdmc
              }
              ]"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" class="pad_bot10 weight7">门店地址</a-col>
      </a-row>
      <a-row>
        <a-col :span="16">
          <a-form-item>
            <a-cascader
              :options="administrativeRegion"
              popupClassName="noChilder"
              @change="onChange"
              placeholder="请选择城市"
              v-decorator="['xzxq', {
                rules: [{ required: true, message: '必填'}],
                initialValue:order&&order.xzxq?[order.xzxq]:[]
              }
              ]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" class="pad_bot10 weight7">详细地址</a-col>
      </a-row>
      <a-row>
        <a-col :span="16" >
          <a-form-item>
            <a-input
              placeholder="请输入详细地址"
              v-decorator="['xxdz', {
                rules: [{ required: true, message: '必填',whitespace: true}],
                initialValue: order&&order.xxdz
              }
              ]"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" class="pad_bot10 weight7">管家信息</a-col>
      </a-row>
      <template v-for="(i,index) in keys">
        <a-row :key="i" v-if="computedDelObj[`${index}`] !=='true'">
          <a-col :span="24">
            <a-row :gutter="12">
              <a-col :span="3">
                <a-form-item>
                  <a-input
                    maxLength="10"
                    v-decorator="[
                      `stewardRequest[${index}].gjxm`,{
                        rules: [{
                          required: true,
                          pattern:nameReg,
                          message: '请输入正确的姓名'
                        }],
                        initialValue: stewardInfo&&stewardInfo.stewardRequest[index]&&stewardInfo.stewardRequest[index].gjxm
                      }
                    ]"
                    placeholder="姓名"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item>
                  <a-input
                    maxLength="11"
                    @blur="handleLxdhBlur"
                    v-decorator="[
                      `stewardRequest[${index}].lxdh`,{
                        rules: [{
                          required: true,
                          pattern: phoneReg,
                          message: '请输入正确的手机号码'
                        },{validator: validatePhone}],
                        initialValue: stewardInfo&&stewardInfo.stewardRequest[index]&&stewardInfo.stewardRequest[index].lxdh,
                        validateFirst:true
                      }
                    ]"
                    placeholder="手机号码"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item>
                  <a-select
                    placeholder="证件类型"
                    v-decorator="[
                      `stewardRequest[${index}].zjzl`,{
                        rules: [{
                          required: true,
                          message: '请选择证件种类'
                        }],
                        initialValue:stewardInfo&&stewardInfo.stewardRequest[index]&&stewardInfo.stewardRequest[index].zjzl||'1'
                      }
                    ]">
                    <a-select-option value="1">二代身份证</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item>
                  <a-row :gutter="12">
                    <a-col :span="12">
                      <a-input
                        maxLength="18"
                        @blur="handleZjhmBlur"
                        v-decorator="[
                          `stewardRequest[${index}].zjhm`,{
                            rules: [{
                              required: true,
                              message: '请输入正确的证件号码',
                              pattern: cardIdReg
                            },{validator: validateId}],
                            initialValue: stewardInfo&&stewardInfo.stewardRequest[index]&&stewardInfo.stewardRequest[index].zjhm,
                            validateFirst:true
                          }
                        ]"
                        placeholder="证件号码"></a-input>
                    </a-col>
                    <a-col :span="6">
                      <div class="person" v-if="index === 0" @click="addTanentInfo"><a-icon :component="iconAddPerson" style="margin-right:5px;"/>增加入住人</div>
                      <div class="person" v-else @click="delTannetInfo(index)"><a-icon :component="iconDelPerson" style="margin-right:5px"/>删除入住人</div>
                    </a-col>
                  </a-row>
                </a-form-item>
                <a-form-item>
                  <a-input
                    type="hidden"
                    v-decorator="[
                      `stewardRequest[${index}].managerId`,{
                        initialValue: stewardInfo&&stewardInfo.stewardRequest[index]&&stewardInfo.stewardRequest[index].managerId
                      }
                    ]"
                    placeholder="管家id"></a-input>
                </a-form-item>
                <a-form-item>
                  <a-input
                    type="hidden"
                    v-decorator="[
                      `stewardRequest[${index}].glId`,{
                        initialValue: stewardInfo&&stewardInfo.stewardRequest[index]&&stewardInfo.stewardRequest[index].glId
                      }
                    ]"
                    placeholder="门店管家关联id"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </template>
    </a-form>
  </div>
</template>
<script>
import { addStore, updateStore } from '@/api/store' // 注意更改
import { nameReg, phoneReg, cardIdReg } from '@/utils/reg'
import { mapGetters, mapActions } from 'vuex'
import { iconAddPerson, iconDelPerson } from '@/core/icons'
import { verifyRepeat } from '@/utils/util'
export default {
  name: 'NewChange',
  props: {
    order: {
      type: Object,
      default: () => { return {} }
    }
  },
  data () {
    return {
      iconAddPerson, // 加图标
      iconDelPerson, // 减图标
      nameReg, // 验证正则
      phoneReg, // 验证正则
      cardIdReg, // 验证正则
      keys: 1, // 加 key 初始化
      newOrderForm: this.$form.createForm(this), // form 初始化
      delObj: {}, // 删除的数据
      selLabel: '', // 选中的的行政区域lable
      deleteId: [] // 删除存在的管家id
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'administrativeRegion' // 行政区域
    ]),
    // 管家信息
    stewardInfo () {
      if (this.order.stewardRequest && this.order.stewardRequest.length > 0) {
        return { stewardRequest: this.order.stewardRequest }
      } else {
        return ''
      }
    },
    // 计算删除的对象
    computedDelObj () {
      return this.delObj
    }
  },
  methods: {
    ...mapActions([
      'getAdministrativeRegion'
    ]),
    handleSubmit (type) {
      return new Promise((resolve, reject) => {
        const order = this.order
        const orderRequest = {
          mdmc: order.mdmc || '', // 门店名称
          xxdz: order.xxdz || '', // 门店详细地址
          xzxq: order.xzxq || '', // 行政辖区code
          xzxqmc: this.selLabel || order.xzxqmc, // 行政辖区名称
          storesId: order.storesId || '', // 门店id(编辑)
          hoperatorId: this.userInfo.id, // 经营者id
          stewardRequest: [] // 管家信息
        }
        this.newOrderForm.validateFieldsAndScroll(async (err, values) => {
          if (!err) {
            orderRequest.stewardRequest = values.stewardRequest
            // 过滤由删除影藏导致的无用数组索引
            const filterStewardRequest = orderRequest['stewardRequest'].filter((item) => {
              if (item) {
                return true
              }
            })
            orderRequest.stewardRequest = filterStewardRequest
            // end
            orderRequest.mdmc = values['mdmc']
            orderRequest.xxdz = values['xxdz']
            orderRequest.xzxq = values['xzxq'][0]
            let res = {}
            if (type === 'Add_STORE') {
              res = await addStore(orderRequest).catch((err) => {
                reject(err)
              })
            } else if (type === 'MODIFIER_STORE') {
              orderRequest.deleteId = this.deleteId // 编辑时传替删除的id
              res = await updateStore(orderRequest).catch((err) => {
                reject(err)
              })
            }
            resolve(res)
          } else {
            reject(err)
          }
        })
      })
    },
    addTanentInfo () {
      this.keys += 1
    },
    delTannetInfo (index) {
      const form = this.newOrderForm
      const deleteglId = form.getFieldValue(`stewardRequest[${index}].glId`)
      if (deleteglId) {
        this.deleteId.push(deleteglId)
      }
      const selObj = { }
      selObj[index] = 'true'
      this.delObj = Object.assign(selObj, this.delObj)
      // 删除自动校验
      this.$nextTick(() => {
        const selArray = form.getFieldValue('stewardRequest')
        for (let i = 0; i < selArray.length; i++) {
          if (selArray[i]) {
            form.validateFields([`stewardRequest[${i}].zjhm`], { force: true })
            form.validateFields([`stewardRequest[${i}].lxdh`], { force: true })
          }
        }
      })
    },
    handleLxdhBlur (e) {
      const form = this.newOrderForm
      const selArray = form.getFieldValue('stewardRequest')
      for (let i = 0; i < selArray.length; i++) {
        if (selArray[i]) {
          if (e.target.id !== `stewardRequest[${i}].lxdh` && e.target.value) {
            form.validateFields([`stewardRequest[${i}].lxdh`], { force: true })
          }
        }
      }
    },
    handleZjhmBlur (e) {
      const form = this.newOrderForm
      const selArray = form.getFieldValue('stewardRequest')
      for (let i = 0; i < selArray.length; i++) {
        if (selArray[i]) {
          if (e.target.id !== `stewardRequest[${i}].zjhm` && e.target.value) {
            form.validateFields([`stewardRequest[${i}].zjhm`], { force: true })
          }
        }
      }
    },
    validatePhone (rule, value, callback) {
      const personalArray = this.newOrderForm.getFieldValue('stewardRequest')
      if (value && personalArray.length > 0) {
        const istrue = verifyRepeat(personalArray, value, rule.field, 1, 'lxdh')
        if (istrue) {
          callback(new Error('联系电话不能重复'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    validateId (rule, value, callback) {
      const formt = this.newOrderForm
      const personalArray = formt.getFieldValue('stewardRequest')
      if (value && personalArray.length > 0) {
        const istrue = verifyRepeat(personalArray, value, rule.field, 1, 'zjhm')
        if (istrue === true) {
          callback(new Error('证件号码不能重复'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    // 城市联动
    onChange (value, selectedOptions) {
      if (selectedOptions) {
        this.selLabel = selectedOptions[0].label
      } else {
        this.selLabel = ''
      }
    }
  },
  created () {
    this.newOrderForm = this.$form.createForm(this)
    if (this.stewardInfo) {
      this.keys = this.stewardInfo.stewardRequest.length
      this.stewardRequest = this.stewardInfo.stewardRequest
    }
    if (!this.administrativeRegion.length > 0) {
      // 获取行政区域
      this.getAdministrativeRegion()
    }
  }
}
</script>
<style lang="less" scoped >
.new-order {
  .fwdz{
    height:24px;
    font-size:16px;
    font-weight:700;
    color:rgba(0,0,0,0.85);
    line-height:24px;
  }
  .person {
    cursor: pointer;
    color: #1890FF;
  }
}
</style>
